﻿function GeoViewPortPicker(controlsId, options) {
    var self = this;
    this.controlsId = controlsId;
    this.options = options;

    this.map = null;
    this.rectangle = null;

    this.initializeMap = function () {
        var mapOptions = { center: new google.maps.LatLng(0, 0), zoom: 0, mapTypeId: google.maps.MapTypeId.ROADMAP };

        this.infoWindow = new google.maps.InfoWindow();
        this.map = new google.maps.Map(document.getElementById(this.controlsId.mapContainerId), mapOptions);

        if (!this.options.viewPort) {
            this.initializeRectangle(this.getDefaultSelection());
            return;
        }

        var viewPort = JSON.parse(this.options.viewPort);
        var initialBounds = new google.maps.LatLngBounds(new google.maps.LatLng(viewPort.southWest.latitude, viewPort.southWest.longitude), new google.maps.LatLng(viewPort.northEast.latitude, viewPort.northEast.longitude));
        this.map.fitBounds(initialBounds);
        this.initializeRectangle(initialBounds);
        this.map.setZoom(viewPort.mapZoom);
    };

    this.showSelectionParameters = function (northWest, southEast) {
        document.getElementById(this.controlsId.inputNorthWestLatId).value = northWest.lat().toString();
        document.getElementById(this.controlsId.inputNorthWestLngId).value = northWest.lng().toString();
        document.getElementById(this.controlsId.inputSouthEastLatId).value = southEast.lat().toString();
        document.getElementById(this.controlsId.inputSouthEastLngId).value = southEast.lng().toString();
    };

    this.getDefaultSelection = function () {
        return new google.maps.LatLngBounds(new google.maps.LatLng(21, -70), new google.maps.LatLng(66, 67));
    };

    this.getRectangleBounds = function () {
        return this.rectangle.getBounds();
    };

    this.getMapZoom = function () {
        return this.map.getZoom();
    };

    this.onRectangleBoundsChanged = function(rectangle) {
        var southWest = rectangle.getBounds().getSouthWest();
        var northEast = rectangle.getBounds().getNorthEast();

        self.showSelectionParameters(new google.maps.LatLng(northEast.lat(), southWest.lng()), new google.maps.LatLng(southWest.lat(), northEast.lng()));
    };

    this.initialize = function () {
        this.initializeMap();
    };

    this.initializeRectangle = function (latLngBounds) {
        var rectangleOptions = {
            bounds: latLngBounds,
            map: this.map,
            editable: true,
            draggable: true
        };

        this.rectangle = new google.maps.Rectangle(rectangleOptions);

        google.maps.event.addListener(this.rectangle, 'bounds_changed', function (event) {
            self.onRectangleBoundsChanged(this);
        });
        self.onRectangleBoundsChanged(this.rectangle);
    };

    this.initialize();
}

